package itbour.onetouchshow.activity.version1_2;


import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.utils.permission.Permission;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.version1_4.V1_4_VideoPreviewActivity;
import itbour.onetouchshow.activity.video.commoninching.CommoninchingActivity;
import itbour.onetouchshow.activity.video.commoninching.CommoninchingPresenter;
import itbour.onetouchshow.activity.video.videobg.VideobgActivity;
import itbour.onetouchshow.base.IntentCode;
import itbour.onetouchshow.bean.inching.noppt.InchingOutLineImgBean;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.constants.platform.WorkPlatform;
import itbour.onetouchshow.listener.OnMultiClickListener;
import itbour.onetouchshow.listener.PermissionListener;
import itbour.onetouchshow.singlecase.InchingDataSingleCase;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.OnMultiClickUtils;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.view.ActivityUtils;
import itbour.onetouchshow.widget.inching.InchingOperaRelativeLayout;
import itbour.onetouchshow.widget.inching.InchingOpreaImageView;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 * 用于竖屏的微调
 */

public class CommoninchingVideoBgActivity extends CommoninchingActivity {


    protected String subType;
    @BindView(R.id.iv_left_bar)
    ImageView igClose;
    @BindView(R.id.id_ig_chage_bg)
    ImageView chageIcon;
    @BindView(R.id.id_ig_del_bg)
    ImageView decIcon;
    /*完成*/
    @BindView(R.id.tv_right_bar)
    TextView tvOver;
    @BindView(R.id.id_ly_edit_bg)
    LinearLayout changeBg;
    @BindView(R.id.id_ly_del_bg)
    LinearLayout delBg;
    @BindView(R.id.id_ed_tv)
    TextView edTv;
    @BindView(R.id.id_tv_del)
    TextView tvDel;
    @BindView(R.id.ly_add_text)
    LinearLayout ly_add_text;
    @BindView(R.id.ly_add_image)
    LinearLayout ly_add_image;
    @BindView(R.id.ly_change_frame)
    LinearLayout ly_change_frame;

    @BindView(R.id.tv_right_delet)
    TextView tv_right_delet;
    @BindView(R.id.ig_left_close)
    ImageView ig_left_close;
    @BindView(R.id.tv_right_save)
    TextView tv_right_save;


    private String docId;
    private int bgId;


    @Override
    @OnClick({R.id.ly_add_text, R.id.ly_add_image, R.id.ly_change_frame})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ly_add_text:
                L_.i("rl_add_text");
                addInchingTextView();
                break;
            case R.id.ly_add_image:
                L_.i("rl_add_image");
                int count = 0;
                //当前页可操作控件总数为20
                //获取传入的加图最大限制
                int ftMaxImageCnt = InchingDataSingleCase.INSTANCE.getLengthControl().getFTMaxImageCnt();
                if (rlInchingBaseArea != null) {
                    for (int i = 0; i < rlInchingBaseArea.getChildCount(); i++) {
                        View childAt = rlInchingBaseArea.getChildAt(i);
                        if (childAt != null && childAt instanceof InchingOperaRelativeLayout) {
                            InchingOperaRelativeLayout rl = (InchingOperaRelativeLayout) childAt;
                            if (rl.getIsEnable() == 1) {
                                if (rl.getData() instanceof InchingOutLineImgBean) {

                                    count++;
                                }
                            }
                        }
                    }
                }
                L_.i("addInchingTextView cout===" + count);
                if (count > ftMaxImageCnt) {
                    new OneToucDialog.Builder(this)
                            .content("图片数量已达到上限")
                            .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(OneToucDialog dialog, DialogAction which) {
                            Log.e("TAH", "点击确定");
                        }
                    }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                            .cancelable(false).setmWidth(AppConst.APP_DIALOG_WIDTH)
                            .show();
                    return;
                }
                //去相册选图
                //吊起取相册的逻辑
                requestPermission(new PermissionListener() {
                    @Override
                    public void onGranted() {
                        // T_.showToastReal("成功");
                        gotoSelectPhotoType(AppConst.TO_ADD_IMAGE);
                    }

                    @Override
                    public void onDenied(List<String> list) {
                        //T_.showToastReal("拒绝");
                    }
                }, Permission.Group.STORAGE);
                break;
            case R.id.ly_change_frame:
                gotoVideobgActivity();
                break;
            default:
                break;
        }
    }


    @Override
    public void loadSucceed(String result) {
        // dismissProgressDialog();
    }

    @Override
    public void loadFaild(String error) {
        dismissProgressDialog();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_video_bg_inching;
    }


    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        mPresenter = new CommoninchingPresenter(this);
        Intent intent = getIntent();
        int intExtra = intent.getIntExtra(IntentCode.TAG, 0);
        bgId = intent.getIntExtra(AppConst.BGID, 0);
        inchType = intent.getIntExtra(IntentCode.INCHING_TYPE, 0);
        subType = intent.getStringExtra(WorkPlatform.TYPE);
        if (subType == null) {
            subType = WorkPlatform.W0RK;
        }
        docId = intent.getStringExtra(AppConst.DOCID);
        // bundle.putString(WorkPlatform.TYPE, WorkPlatform.W0RK);
        mPresenter.setId(Integer.valueOf(docId));
        showProgressDialogWithText("数据加载中...");

        initPresenterType(intExtra);
        initOnClickListener();
        //全屏Activity操作
        getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        getToolBarView().setVisibility(View.GONE);
    }


    /**
     * 根据类别请求不同数据
     *
     * @param intExtra
     */
    public void initPresenterType(int intExtra) {
        if (intExtra == IntentCode.INTENT_VERTICAL_VIDEP) {
            mPresenter.setDocId(Integer.valueOf(docId));
            //作品还是模板
            if (subType.equals(WorkPlatform.W0RK)) {
                mPresenter.onVerticalVideoBgEnter(bgId, 0);
            } else {
                mPresenter.onVerticalVideoBgEnter(bgId, 1);
            }
        }
    }

    public void initOnClickListener() {
        getToolBarView().setVisibility(View.GONE);
        edTv.setText("删除边框");
        decIcon.setImageResource(R.mipmap.video_chage_icon);
        changeBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (OnMultiClickUtils.isFastClick()) {
                    mPresenter.deleteVideoBg(docId);
                }
            }
        });

        tv_right_delet.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                mPresenter.deleteVideoBg(docId);
            }
        });

        chageIcon.setImageResource(R.mipmap.video_del_icon);
        tvDel.setText("更换边框");
        delBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoVideobgActivity();
            }
        });

        if (subType.equals(WorkPlatform.W0RK)) {
            tv_right_delet.setVisibility(View.VISIBLE);
            chageIcon.setImageResource(R.mipmap.video_del_icon);
            changeBg.setEnabled(true);
        } else {
            tv_right_delet.setVisibility(View.GONE);
            edTv.setTextColor(UIUtils.getColor(R.color.tab_color_false));
            chageIcon.setImageResource(R.mipmap.video_un_del_icon);
            changeBg.setEnabled(false);
        }


        tv_right_save.setText("保存");
        tv_right_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //视频背景
                mPresenter.updateVideoDocBg_v1_2();
            }
        });

        tvOver.setText("保存");
        tvOver.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //视频背景
                mPresenter.updateVideoDocBg_v1_2();
            }
        });

        ig_left_close.setImageResource(R.mipmap.cancle_icon);
        ig_left_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.popAllActivityUntillOne(V1_4_VideoPreviewActivity.class);
            }
        });
        igClose.setImageResource(R.mipmap.cancle_icon);
        igClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.popAllActivityUntillOne(V1_4_VideoPreviewActivity.class);
            }
        });
    }


    @Override
    public void onSaveCaoGaoClick() {
        isSave = true;
        showProgressDialogWithText("正在存草稿");
        mPresenter.updateVideoDocBg_v1_2();
    }


    private void gotoVideobgActivity() {
        Bundle bundle = new Bundle();
        L_.e("afterCreate showBgDialog id :" + docId);
        bundle.putString(AppConst.DOCID, docId);
        //bundle.putString(AppConst.DOCID, videoPreviewBean.getId() + "");
        bundle.putString(WorkPlatform.TYPE, subType);
        //openActivity(VideobgActivity.class, bundle);
        Intent intent = new Intent(CommoninchingVideoBgActivity.this, VideobgActivity.class);
        intent.putExtras(bundle);
        startActivityForResult(intent, 20000);
    }

    @Override
    public void toUpVideoBgSuccess(String result) {
        UserMakeTag userMakeTag = UserMakeTag.SETBG;
        EventBus.getDefault().post(userMakeTag);
        ActivityUtils.popAllActivityUntillOne(V1_4_VideoPreviewActivity.class);
    }

    @Override
    protected void initTitle() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Settings.System.canWrite(this);
        }
        getToolBarView().setTitleTextColor(UIUtils.getColor(R.color.white)).
                setBackgroundColor(UIUtils.getColor(R.color.black));
        setImmersionBarBlack();

        getToolBarView().setLetfIocnOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jugleQuit();
            }
        });
        getToolBarView().setVisibility(View.GONE);
        registerExitReceiver();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 20000 & data != null) {
            int intExtra = data.getIntExtra(IntentCode.TAG, 0);
            bgId = data.getIntExtra(AppConst.BGID, 0);
            inchType = data.getIntExtra(IntentCode.INCHING_TYPE, 0);
            subType = data.getStringExtra(WorkPlatform.TYPE);
            docId = data.getStringExtra(AppConst.DOCID);
            mPresenter.setId(Integer.valueOf(docId));
            showProgressDialogWithText("数据加载中...");
            mPresenter.setDocId(Integer.valueOf(docId));
            //作品还是模板
            if (subType.equals(WorkPlatform.W0RK)) {
                mPresenter.onVerticalVideoBgEnter(bgId, 0);
            } else {
                mPresenter.onVerticalVideoBgEnter(bgId, 1);
            }
        }
    }

    @Override
    public void deleteVideoBgSuccess() {
        // EventBus.getDefault().post(1800);
        UserMakeTag userMakeTag = UserMakeTag.SETBG;
        EventBus.getDefault().post(userMakeTag);
        ActivityUtils.popAllActivityUntillOne(V1_4_VideoPreviewActivity.class);
    }


    /**
     * 要怎么做边界控制？
     * <p>
     * 之前的做法
     * 基础绘图区域加上了半个控制图标的宽高
     * 设定一个容器 容器的宽高加上了控制图标的宽高
     * 可编辑标记的虚线和拖动的控制控件 和展示控件在里面
     * <p>
     * 问题
     * 1：可编辑标记虚线应该怎么放
     * 2：控制控件应该怎么放
     * 3：视频的不可编辑区域应该怎么处理
     * <p>
     * 1:可编辑标记虚线作为bitmap的一部分绘制上去
     * 2:控制控件 放在基础绘图去的外层
     * 3：不可编辑的区域在基础绘图区判断
     * 4:图片在控制点区域内拖动时 蒙板实时改变 应该怎么处理
     *
     * @param data
     */
    @Override
    public void createOperaImage(InchingOutLineImgBean data) {
        int w = (int) Math.ceil(data.getPos().getW());
        int h = (int) Math.ceil(data.getPos().getH());
        int x = (int) data.getPos().getX();
        int y = (int) data.getPos().getY();
        int editable = data.getEditable();
        String source = data.getSource();


        InchingOperaRelativeLayout operaViewRL = getInchingRL(x, y, w, h);
        operaViewRL.setData(data);

        L_.e("createOperaImage" + source);
        showProgressDialogWithText("加载中");
        /***
         * 加载背景图片
         */
        Glide.with(this).asBitmap().load(source).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                InchingOpreaImageView img = new InchingOpreaImageView(CommoninchingVideoBgActivity.this);
                img.setId(R.id.inching_can_opear_img);
                RelativeLayout.LayoutParams inchingRLLP = getInchingRLLP(w, h);
                operaViewRL.addView(img, inchingRLLP);
                img.setImgBitmap(resource);
                img.setData(data);
                dismissProgressDialog();
                if (editable == 1) {
                    operaViewRL.setThisDottedLineIsShow(1);

                    operaViewRL.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            operaViewRL.setThisDottedLineIsShow(0);
                            InchingOperaRelativeLayout nowSelectView = getNowSelectView();
                            if (nowSelectView != null && nowSelectView != operaViewRL) {
                                nowSelectView.setThisDottedLineIsShow(1);
                            }
                            setNowSelectView(operaViewRL);
                            //当再次点击时要取现在的数据
                            InchingOutLineImgBean nowData = (InchingOutLineImgBean) operaViewRL.getData();

                            int[] locationMove = new int[2];
                            operaViewRL.getLocationOnScreen(locationMove);//获取在整个屏幕内的绝对坐标
                            int viewInWindowsX = locationMove[0];
                            int viewInWindowsY = locationMove[1];
                            showPopWindow(nowData, viewInWindowsX, viewInWindowsY, nowSelectView);


                        }
                    });
                }


            }
        });


    }


}
